<template>
  <div class="app-container">
    <el-form :inline="true" label-width="68px" v-if="showSearch">
      <el-form-item label="商品名称" size="small">
        <el-input placeholder="请输入商品名称" v-model="queryParams.name"></el-input>
      </el-form-item>
      <el-form-item label="品牌" size="small">
        <el-select
            v-model="queryParams.brandId"
            placeholder="请选择"
            style="width: 240px"
        >
          <el-option
              v-for="(item,index) in brandList"
              :key="index"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分类" size="small">
        <el-select
            v-model="queryParams.categoryId1"
            @change="getCategoryList1"
            placeholder="请选择"
            style="width: 240px"
        >
          <el-option
              v-for="(item,index) in categoryList1"
              :key="index"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
        <el-select
            v-model="queryParams.categoryId2"
            placeholder="请选择"
            @change="getCategoryList2"
            :disabled="!queryParams.categoryId1"
            style="width: 240px"
        >
          <el-option
              v-for="(item,index) in categoryList2"
              :key="index"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
        <el-select
            v-model="queryParams.categoryId3"
            placeholder="请选择"
            :disabled="!queryParams.categoryId2"
            style="width: 240px"
        >
          <el-option
              v-for="(item,index) in categoryList3"
              :key="index"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getList">搜索</el-button>
        <el-button icon="Refresh" @click="doReset()">重置</el-button>
      </el-form-item>
    </el-form>
    <el-form :inline="true" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleChange">修改</el-button>
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
        <el-tooltip circle :content="showCircle" placement="top">
          <el-button circle icon="Search" @click="change()"></el-button>
        </el-tooltip>
        <el-button icon="Refresh" circle @click="getList"/>
      </el-form-item>

    </el-form>

    <!--    表格数据-->
    <el-table :data="productList" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column prop="id" label="ID" width="55"/>
      <el-table-column prop="sliderUrls" label="轮播图" width="260" #default="scope">
        <img v-for="(item,index) in scope.row.sliderUrls" :src="item" :key="index" width="30">
      </el-table-column>
      <el-table-column prop="name" label="商品名称" width="160"/>
      <el-table-column prop="brandName" label="品牌" width="100"/>
      <el-table-column prop="category1Name" label="一级分类" width="120"/>
      <el-table-column prop="category2Name" label="二级分类" width="120"/>
      <el-table-column prop="category3Name" label="三级分类" width="120"/>
      <el-table-column prop="unitName" label="计量单位" width="120"/>
      <el-table-column prop="status" label="状态" width="120" #default="scope">
        <span v-if="scope.row.status==1">已上架</span>
        <span v-else>未上架</span>
      </el-table-column>
      <el-table-column prop="auditMessage" label="审核状态" width="120"/>
      <el-table-column label="操作"
                       align="center"
                       class-name="small-padding fixed-width"
                       #default="scope">
        <span v-if="scope.row.auditMessage=='审批通过'">
          <el-button link
                     type="primary"
                     icon="Edit"
                     v-if="scope.row.status=='1'"
                     @click="changeStatus(scope.row)"
          >下架</el-button>
          <el-button link
                     type="primary"
                     icon="Edit"
                     v-else @click="changeStatus(scope.row)"
          >上架</el-button>
        </span>
        <span v-if="scope.row.auditMessage=='未审核'">
        <el-button link type="primary" icon="Edit" @click="handleChange">修改</el-button>
        <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        <el-button link type="success" icon="Delete" @click="pass(scope.row,true)">通过</el-button>
        <el-button link type="danger" icon="Delete" @click="pass(scope.row,false)">驳回</el-button>
        </span>
        <span v-if="scope.row.auditMessage=='驳回'"/>
      </el-table-column>
    </el-table>

    <!--    新增或修改的对话框-->
    <el-dialog
        v-model="open"
        :title="title"
        width="1100"
    >
      <span>
        <el-steps style="max-width: 1100px" :active="active" finish-status="success">
        <el-step title="Step 1" description="商品基本信息"/>
        <el-step title="Step 2" description="商品SKU信息"/>
        <el-step title="Step 3" description="商品详情"/>
        </el-steps>
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="pre">上一步</el-button>
          <el-button type="primary" @click="next">下一步</el-button>
          <el-button type="primary">提交</el-button>
          <el-button @click="reset()">取消</el-button>
        </div>
      </template>
      <hr>
      <div class="app-container" v-if="active==0">
        <el-form>
          <el-form-item label="商品名称">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="分类">
            <el-cascader
                :props="categoryProps"
                v-model="form.categoryIdList"
                placeholder="请选择"
                @change="handleCategoryChange"
                style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="品牌">
            <el-select placeholder="选择品牌" v-model="form.categoryBrandId">
              <el-option v-for="(item,index) in categoryBrandList"
                         :key="index"
                         :value="item.id"
                         :label="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="计量单位">
            <el-select placeholder="计量单位" v-model="form.unitId">
              <el-option v-for="(item,index) in unitList"
                         :key="index"
                         :value="item.id"
                         :label="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="轮播图">
            <el-upload
                v-model="sliderUrlList"
                :action="imgUpload.url"
                list-type="picture-card"
                :headers="imgUpload.headers"
                :on-success="handleAddList"
                :on-remove="handleRemove"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <div v-if="active==1">
        <el-form>
          <el-form-item label="选择规格">
            <el-select placeholder="选择规格" v-model="form.productSpecId">
              <el-option v-for="(item,index) in productSpecsList"
                         :key="index"
                         :value="item.id"
                         :label="item.specName"
                         @click="getSkuSpecList(form.productSpecId)"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品SKU">
              <el-table :data="form.productSkuList" style="width: 100%">
                <el-table-column prop="skuSpec" label="规格" width="180" />
                <el-table-column prop="name" label="图片" width="180" >
                  <el-upload
                      class="avatar-uploader"
                      action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess"
                      :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  </el-upload>
                </el-table-column>
                <el-table-column prop="price" label="售价" />
                <el-table-column prop="address" label="市场价" />
                <el-table-column prop="address" label="成本价" />
                <el-table-column prop="address" label="库存数" />
                <el-table-column prop="address" label="重量" />
                <el-table-column prop="address" label="体积" />
              </el-table>
          </el-form-item>
        </el-form>
      </div>
      <div v-if="active==2">
        第三步
      </div>
    </el-dialog>

    <!--    分页-->
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    queryParams.value.categoryId1{{ queryParams.categoryId1 }}<br>
    queryParams.value.categoryId2{{ queryParams.categoryId2 }}<br>
    queryParams.value.categoryId3{{ queryParams.categoryId3 }}<br>
    ids{{ ids }}<br>
    active{{ active }}<br>
    form.value.categoryId{{ form.categoryId }}<br>
    form.value.categoryIdList{{ form.categoryIdList }}<br>
    form.value.brandId{{ form.brandId }}<br>
    form.value.unitId{{ form.unitId }}<br>
    sliderUrlList.value{{ sliderUrlList }}<br>
    form.value.categoryBrandId{{ form.categoryBrandId }}<br>
    productSpecsList.value{{ productSpecsList }}<br>
    form.value.productSpecId{{ form.productSpecId }}<br>
    specValue====={{specValue}}
  </div>
</template>
<script setup>
import {ref, reactive, toRefs} from "vue";
import {getAllBrand, listBrand} from '@/api/product/brand'
import {listCategory} from '@/api/product/categorybrand'
import {listProduct, deleteProduct, updateStatus, updateAuditStatus} from '@/api/product/product'
import {listAllUnit} from '@/api/product/unit'
import {getToken} from "@/utils/auth";
import {ElMessage, ElMessageBox} from "element-plus";
import {listCategoryBrandByCategoryId} from "@/api/product/categorybrand";
import {productSpecListByCategoryId} from "../../../api/product/productSpec.js";


const total = ref(0)
const data = reactive({
  //查询参数
  queryParams: {
    name: undefined,
    pageNum: undefined,
    pageSize: undefined,
    brandId: undefined,
    categoryId1: undefined,
    categoryId2: undefined,
    categoryId3: undefined
  },
  //增加或修改提交的参数
  form: {},
  imgUpload: {
    // 设置上传的请求头部
    headers: {
      Authorization: "Bearer " + getToken()
    },
    // 图片上传的方法地址:
    url: import.meta.env.VITE_APP_BASE_API + "/file/upload"
  }
})

/** */
//品牌
const {queryParams, form, imgUpload} = toRefs(data)
const brandList = ref()

function getBrandList() {
  getAllBrand().then(response => {
    brandList.value = response.data
  })
}

getBrandList()


//分类
const categoryList1 = ref()
const categoryList2 = ref()
const categoryList3 = ref()
const parent = ref(0)

function getCategoryList() {
  listCategory(parent.value).then(response => {
    categoryList1.value = response.data
  })
}

function getCategoryList1() {
  listCategory(queryParams.value.categoryId1).then(response => {
    categoryList2.value = response.data
    queryParams.value.categoryId2 = null
    queryParams.value.categoryId3 = null
  })
}

function getCategoryList2() {
  listCategory(queryParams.value.categoryId2).then(response => {
    categoryList3.value = response.data
    queryParams.value.categoryId3 = null
  })
}

getCategoryList()


//是否显示搜索
const showCircle = ref("隐藏搜索框")
const showSearch = ref(true)

function change() {
  if (showCircle.value == "隐藏搜索框") {
    showSearch.value = false
    showCircle.value = "显示搜索框"
  } else if (showCircle.value == "显示搜索框") {
    showSearch.value = true
    showCircle.value = "隐藏搜索框"
  }
}


//功能按钮
//重置
function doReset() {
  queryParams.value.categoryId1 = null
  queryParams.value.categoryId2 = null
  queryParams.value.categoryId3 = null
  queryParams.value.pageNum = 1
  queryParams.value.pageSize = 10
  queryParams.value.brandId = null
  queryParams.value.name = null
  getList()
}

//删除
function handleDelete(row) {

  const _id = row.id || ids.value
  ElMessageBox.confirm(
      "确定要删除编号为:" + _id + "的商品码?",
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    deleteProduct(_id).then(() => {
      ElMessage({
        type: "success",
        message: "删除成功"
      })
      getList()
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除'
    })
  })


}


//表格
const ids = ref()
const id = ref()
const single = ref(true)
const multiple = ref(true)
const productList = ref([])

function getList() {
  listProduct(queryParams.value).then(response => {
    total.value = response.total
    productList.value = response.rows
    productList.value.forEach(item => {
      item.sliderUrls = item.sliderUrls.split(",")
    })
  })
}

//表格多选
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  id.value = selection.map(item => item.id)
  multiple.value = !selection.length
  single.value = selection.length != 1
}

//商品上下加
const statusMsg = ref()

function changeStatus(row) {
  if (row.status == 1) {
    statusMsg.value = "下架"
  }
  if (row.status != 1) {
    statusMsg.value = "上架"
  }
  ElMessageBox.confirm(
      "确定要" + statusMsg.value + "编号为:" + row.id + "的商品吗?",
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    if (row.status == 1) {
      updateStatus(row.id, -1).then(response => {
        ElMessage({
          type: 'success',
          message: '操作成功',
        })
        getList()
      })

    } else {
      updateStatus(row.id, 1).then(response => {
        ElMessage({
          type: 'success',
          message: '操作成功',
        })
        getList()
      })
    }
  })
}

//审核通过
const passMsg = ref()

function pass(row, boolean) {
  if (boolean) {
    passMsg.value = "通过"
  }
  if (!boolean) {
    passMsg.value = "驳回"
  }
  ElMessageBox.confirm(
      "确定要" + passMsg.value + "编号为:" + row.id + "的商品吗?",
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    if (boolean) {
      updateAuditStatus(row.id, 1).then(response => {
        ElMessage({
          type: 'success',
          message: '操作成功',
        })
        getList()
      })

    } else {
      updateAuditStatus(row.id, -1).then(response => {
        ElMessage({
          type: 'success',
          message: '操作成功',
        })
        getList()
      })
    }
  })
  getList()
}


//dialog对话框新增或修改
const open = ref(false)
const title = ref()

//三级分类
const props = {
  lazy: true,
  value: 'id',
  label: 'name',
  leaf: 'leaf',
  async lazyLoad(node, resolve) {
    if (typeof node.value == 'undefined') node.value = 0
    const {data} = await listCategory(node.value)
    data.forEach(item => {
      item.leaf = !item.hasChildren
    })
    resolve(data)
  }
}
const categoryProps = ref(props)

//重置对话框数据
function reset() {
  form.value.categoryId = null
  form.value.categoryIdList = null
  active.value = 0
  form.value.brandId = null
  open.value = false
  sliderUrlList.value = null
  form.value.categoryBrandId = null
  productSpecsList.value = null
  form.value.productSpecId = null
  form.value.unitId = null

}

function handleAdd() {
  reset()
  getUnitList()
  open.value = true
  title.value = "新增商品"
}

function handleChange() {
  reset()
  getUnitList()
  open.value = true
  title.value = "修改商品"
}

//上一步
const active = ref(0)

function pre() {
  if (active.value <= 0) {
    active.value = 0
  } else {
    active.value = active.value - 1
  }
}

//下一步
function next() {
  if (active.value >= 2) {
    active.value = 2
  } else {
    active.value = active.value + 1
  }
}

//三级联动发生改变
function handleCategoryChange() {
  if (form.value.categoryIdList.length == 3) {
    form.value.categoryId = form.value.categoryIdList[2]
    getCategoryBrandList(form.value.categoryId)
    getProductSpecList(form.value.categoryId)
  }
}

//获取单位列表
const unitList = ref()

function getUnitList() {
  listAllUnit().then(response => {
    unitList.value = response.data
  })
}

//获取分类品牌列表
const categoryBrandList = ref([])

function getCategoryBrandList(id) {
  listCategoryBrandByCategoryId(id).then(response => {
    categoryBrandList.value = response.data
  })
}

//获取商品规格列表
const productSpecsList = ref([])

function getProductSpecList(id) {
  productSpecListByCategoryId(id).then(response => {
    productSpecsList.value = response.data
    productSpecsList.value.forEach(item=>{
      item.specValue = JSON.parse(item.specValue)
    })
    console.log(productSpecsList.value)
  })
}


const specValue = ref()
const ps = ref()
function getSkuSpecList(productSpecId) {
  if(item=>item.id == form.value.productSpecId!=null) {
     ps.value= productSpecsList.value.find(item=>item.id == form.value.productSpecId)
    //三维数组
    specValue.value = ps.value.specValue
    //获取skuSpecList
    form.value.productSkuList = []
    let array = []
    specValue.value.forEach(item=>{
      let res = []
      item.valueList.map(x=>{
        res.push(x)
      })
      array.push(res)
    })
    //取笛卡尔积
    let result = array.reduce(
        (a, b, c) => {
          let res = []
          a.map(x => {
            b.map(y => {
              res.push([...x, y])
            })
          })
          return res
        },
        [[]]
    )
    console.log(result)
    result.forEach(item=>{
      form.value.productSkuList.push({
        skuSpec: item.join(' + '),
        skuSpecList: item,
        price: 0,
      })
    })
    console.log("specValue")
    console.log(form.value.productSkuList)
  }
}


//图片上传
const sliderUrlList = ref([])

function handleAddList(response) {
  sliderUrlList.value.push(response.data.url)
}

function handleRemove(uploadFile) {
  sliderUrlList.value.splice(sliderUrlList.value.indexOf(uploadFile.response.data.url), 1)
}

getList()
</script>